<template>
<view>
<!-- 外卖模式的点单 --> 

<view class="waimaiContainer">
  <!-- 左边的导航 -->  
  <view class="shop_top" :style="'background:' + setting.platformSetting.defaultColor + ';'">
    <view class="shop_top_left">
      <block v-if="shopInfo.shopLogo!=''">
         <image class="shop_top_img" :src="shopInfo.shopLogo"></image>
       </block>
      <block v-else>
         <image class="shop_top_img" :src="setting.platformSetting.logo"></image>
      </block>
    </view>
    <view class="shop_top_right">
      <view class="shop_top_name"><text>{{shopInfo.shopName}}</text></view>
      <view class="shop_top_decribe">
        <text class="decribe_dada">达达专送-46分钟</text>
        <text class="decribe_base">| 基础运费4元</text>
      </view>
    </view>
  </view> 
  <scroll-view scroll-y class="leftScrollType">
     <view :class="(allPro?'activeTypeItem':'TypeItem')" data-type="all" @tap="bindTypeItem" data-index="0">全部</view>  
     <view v-for="(type, index) in shopInfo.shopTypes" :key="index" :data-type="type" :data-index="index" @tap="bindTypeItem" :class="(type.active?'activeTypeItem':'TypeItem')">
        <!-- <block wx:if='{{!!type.typeIcon}}'>
          <image class='TypeItem_iamge' mode='aspectFit' src='{{type.typeIcon}}'></image>
        </block>
        <block wx:else></block> -->
        <text>{{type.typeName}}</text>
        <block v-if="type.hasInCartCount > 0">
          <view class="countNumTag countNumInLeft">{{type.hasInCartCount}}</view>
        </block>
        </view>
      
      <view class="ToOrderView_container">
        <block v-if="pushItem.length > 0">
          <view class="ToOrderView ToOrderView1" data-link="order_list_0.html?easyStatusName=全部订单&easyStatus=0" @tap="toOrderPage" :style="'background:' + setting.platformSetting.defaultColor + ';'">
            <image mode="aspectFill" src="https://image1.sansancloud.com/xianhua/2019_12/16/15/54/40_186.jpg?x-oss-process=style/preview_120"></image>
            <text>订单</text>
          </view>
        </block>
        <block v-else>
        <view class="ToOrderView ToOrderView2" data-link="order_list_0.html?easyStatusName=全部订单&easyStatus=0" @tap="toOrderPage" :style="'background:' + setting.platformSetting.defaultColor + ';'">
          <image mode="aspectFill" src="https://image1.sansancloud.com/xianhua/2019_12/16/15/54/40_186.jpg?x-oss-process=style/preview_120"></image>
          <text>订单</text>
        </view>
       </block>
      </view>
       
      <view class="bottomHeight"></view>
  </scroll-view>

  <!-- 右边的商品列表 -->
  <scroll-view scroll-y @scrolltolower="onReachBottom2" class="RightProductContainer">
    <view v-if="!shopProList" class="none">
      <image mode="widthFix" src="https://image1.sansancloud.com/xianhua/2019_12/17/11/9/46_337.jpg?x-oss-process=style/preview_120"></image>
      <text>没有相关商品</text>
    </view>
    <view class="productItem" v-for="(result, index) in shopProList" :key="index" :data-info="result" @tap="toProductDetail">
        <view class="productItemImage">
          <image mode="aspectFill" :src="result.imagePath + '?x-oss-process=style/preview'"></image>
        </view>
        <view class="productInfo">
          <view class="productInfo_name">{{result.name}}</view>
          <view class="productInfo_decribe">
            <text class="small_decribe">月售100件|好评99.9%</text>
            <text class="productInfo_promotionName" v-if="result.promotionName">{{result.promotionName}}</text>
          </view>
          <view class="productInfo_Price">

            <view>￥<text class="PRICE">{{result.price}}</text> </view>
            <view class="productInfo_Nums">
              <block v-if="!result.measureItem">
                <block v-if="result.inCarCount>0">
                  <image src="https://image1.sansancloud.com/xianhua/2019_12/16/15/55/32_567.jpg?x-oss-process=style/preview_120" :data-id="index" @click.stop="subNum"></image>
                  <text class="font1">{{result.inCarCount}}</text>
                </block>
                <image src="https://image1.sansancloud.com/xianhua/2019_12/16/15/55/32_666.jpg?x-oss-process=style/preview_120" :data-id="index" @click.stop="addNum"></image>
              </block>
              <block v-else>
                <block v-if="result.inCarCount>0">
                  <view class="PRICE"> {{result.inCarCount}}</view>
              </block>
                <view class="choose_measureItem" :data-id="index" @click.stop="chooseMeasureItem">选规格</view>
                </block>
            </view>

          </view>
        </view>
    </view>
    <view class="bottomHeight"></view>
  </scroll-view>


</view>

  <block v-if="pushItem.length > 0">
  <view class="bottomCartContainer" :style="'background:' + setting.platformSetting.defaultColor + ';'">
    <view class="cartInfo" @tap="showZheshao">
       <view class="imageCartContainer flexCenter">
         <image src="https://image1.sansancloud.com/xianhua/2019_12/16/15/56/3_253.jpg?x-oss-process=style/preview_120"></image>
         <view class="countCartNum">{{countGood}}</view>
       </view>
       <view class="Price">￥<text class="PRICE">{{countPrice}}</text></view>
    </view>
    <view class="sureButn" @tap="createOrder">选好了</view>
  </view>
  </block>

<view v-if="pushItem.length > 0" class="waimai_cart_container_forTap"> 
    <view class="Tap_cart">
      <block v-if="!showType"><view class="Tap_cart_v1" :style="'background:' + setting.platformSetting.defaultColor + ';'" @tap="showZheshao">^</view></block>
      <block v-else><view class="Tap_cart_v2" @tap="showZheshao">v</view> </block>
     </view>
  <scroll-view scroll-y class="waimai_cart_container" :animation="animationData">
    <view class="waimai_cart_item" v-for="(cartI, index) in pushItem" :key="index">
        <view class="waimai_cart_item_info">
          <view class="waimai_cart_item_info_name">{{cartI.name}}</view>
          <block v-if="!!cartI.measureCartensian">
          <view class="waimai_cart_item_info_measureCartensian">
            <view v-for="(mesure, index2) in cartI.measureCartensian.measurements" :key="index2">{{mesure.measureName}}</view>
          </view>
          </block>
          <view class="waimai_cart_item_info_price">
            ￥<text class="waimai_cart_item_info_price2">{{cartI.price}}</text>
          </view>
        </view>
        <view class="waimai_cart_item_nums">
                <image src="https://image1.sansancloud.com/xianhua/2019_12/16/15/55/32_567.jpg?x-oss-process=style/preview_120" :data-id="index" @click.stop="subCartNum"></image>
                <text class="font1">{{cartI.count_offline}}</text>
            
              <image src="https://image1.sansancloud.com/xianhua/2019_12/16/15/55/32_666.jpg?x-oss-process=style/preview_120" :data-id="index" @click.stop="addCartNum"></image>
        </view>
    </view>
  </scroll-view>
</view>

<view class="zhezhao" v-if="showType" @tap="closeZhezhao"></view>


<!-- 规格 -->
  <view v-if="showGuigeType" class="measureItemsContainer">
    <view class="measureItemsCard">
      <view class="cardHead">
        <view class="cardHeadTip"><view></view><view></view><view></view></view>
        <view class="cardHeadName">{{MeasureItem.name}}</view>
        <view class="closeCard" @tap="closeGuigeZhezhao">
         <icon type="clear" color="red" size="23"></icon>
        </view>
      </view>
      <view class="cardMid" v-for="(types, index) in MeasureItem.measureTypes" :key="index">
        <view class="cardMidName">{{types.name}}</view>
        <radio-group class="cardMidGuigeContainer" :name="types.name" @change="chooseMeasure">
          <label v-for="(Measure, i) in types.productAssignMeasure" :key="i" :data-index="index + '-' + i" @tap="radioChange">
            <view :class="(types.checkedMeasureItem == i? 'active':'')">{{Measure.measureName}}</view>
            <radio :checked="types.checkedMeasureItem == i" :value="Measure.measureTypeName + '-' + Measure.id" hidden="true"></radio>
          </label>
        </radio-group>
      </view>
     
      <view class="submitMeasure">
        <view class="submitMeasure_price">￥ <text class="PRICE">{{measurementJson.price}}</text></view>
        <view class="submitMeasure_addto" @tap="submitMeasure">加入购物车</view>
      </view>

    </view>
  </view>

<view class="zhezhao" v-if="showGuigeType"></view>
</view>
</template>

<script>

export default {
  data() {
    return {
      animationData: {},
      setting: null,
      // setting   
      productData: [],
      // 商品数据 
      sysWidth: 320,
      //图片大小
      tab: '',

      /* 显示或影藏 */
      showType: false,
      show0: false,
      show1: false,
      show2: false,
      shopInfo: null,
      shopProList: null,
      proTypeState: false,
      allPro: true,
      topName: {
        SearchProductName: "" //头部搜索的

      },
      focusTypeItem: null,
      bindProductTypeIndex: null,
      ProductshowWay: 1,
      // ProductshowWay列表显示方法 
      typeSearch: '',
      // typeSearch的字体 
      canRefresh: true,

      /* 购物车 */
      cart: [],
      pushItem: [],
      countGood: 0,
      countPrice: 0,
      //规格
      showGuigeType: false,
      checkedMeasureItem: 0,
      MeasureItem: null,
      measurementJson: {
        price: 0
      } //规格价格
      ,

      /* 全部参数 */
      params: {
        categoryId: "",
        platformNo: "",
        belongShop: "",
        typeBelongShop: "",
        page: 1,
        showType: "",
        showColumn: "",
        productName: "",
        startPrice: "",
        endPrice: "",
        orderType: "",
        saleTypeId: "",
        promotionId: "",
        shopProductType: "",
        needCarCount: 1
      },

      /* 创建订单 */
      postCarItemJson: {
        shopId: '',
        orderType: ''
      },
      listPage: {
        page: 1,
        pageSize: 0,
        totalSize: 0,
        curpage: 1
      },
      shopCount: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("===options=====", options);
    var that = this;

    if (!getApp().globalData.setting) {
      console.log('-------------hasNoneSetting-----------');
      getApp().globalData.getSetting(that);
    } else {
      console.log('-------------hasSetting-----------');
      this.setData({
        setting: getApp().globalData.setting
      });
      console.log(this.setting);
    }

    this.setData({
      pushItem: getApp().globalData.cart_offline
    });
    console.log("app.cart_offline", getApp().globalData.cart_offline);
    this.params.belongshop = options.addShopId;
    this.params.shopProductType = 0;
    this.getShopTypeData(options); // this.getShopListData(this.params,2)
    // 查找缓存(先暂时把id当成桌号，后台暂时没有配置桌号)

    try {
      var tableID = wx.getStorageSync('tableID');

      if (value) {// Do something with return value
      }
    } catch (e) {// Do something when catch error
    }

    console.log("=========tableID===========", tableID);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // this.listPage.page = 1
    // this.params.page = 1
    // this.getData(this.params, 2)
    wx.showNavigationBarLoading();
    wx.hideNavigationBarLoading(); //完成停止加载

    wx.stopPullDownRefresh(); //停止下拉刷新
  },
  methods: {
    setAppCart: function () {
      getApp().globalData.cart_offline = this.pushItem;
    },
    //跳转到订单页面
    toOrderPage: function (e) {
      let linkUrl = e.currentTarget.dataset.link;
      getApp().globalData.linkEvent(linkUrl);
    },

    /* 点击遮罩层 */
    closeZhezhao: function () {
      this.getShopListData(this.params, 2);
      this.setData({
        showType: false
      });
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease-out'
      });
      animation.height(0).step();
      this.setData({
        animationData: animation.export()
      });
    },
    showZheshao: function () {
      this.setData({
        pushItem: this.pushItem
      });
      this.setData({
        showType: !this.showType
      });
      let showType2 = this.showType;
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease-in-out'
      });

      if (showType2) {
        animation.height(250).step();
      } else {
        animation.height(0).step();
      }

      this.setData({
        animationData: animation.export()
      });
    },

    /* 点击分类大项 */
    bindTypeItem: function (event) {
      this.listPage.page = 1;
      this.params.page = 1;
      console.log('======1======', event.currentTarget.dataset);

      if (event.currentTarget.dataset.type === 'all') {
        console.log("-=======this.data.shopInfo=========", this.shopInfo);
        let belongShop = this.shopInfo.id;
        let shopProductType = event.currentTarget.dataset.index;
        let param = Object.assign({}, param, {
          belongShop: belongShop,
          shopProductType: shopProductType
        });
        this.setData({
          allPro: true
        });

        for (let i = 0; i < this.shopInfo.shopTypes.length; i++) {
          this.shopInfo.shopTypes[i].active = false;
        }

        this.setData({
          shopInfo: this.shopInfo
        });
        this.getShopListData(param, 2);
      } else {
        let belongShop = event.currentTarget.dataset.type.belongShopId;
        let shopProductType = event.currentTarget.dataset.type.id;
        let param = Object.assign({}, param, {
          belongShop: belongShop,
          shopProductType: shopProductType
        });
        this.setData({
          allPro: false
        });

        for (let i = 0; i < this.shopInfo.shopTypes.length; i++) {
          if (this.shopInfo.shopTypes[i].id == event.currentTarget.dataset.type.id) {
            this.shopInfo.shopTypes[i].active = true;
          } else {
            this.shopInfo.shopTypes[i].active = false;
          }
        }

        console.log("this.data.shopInfo.shopTypes", this.shopInfo.shopTypes);
        this.setData({
          shopInfo: this.shopInfo
        });
        this.getShopListData(param, 2);
      }
    },
    ChangeParam: function (params) {
      var returnParam = "";

      for (let i in params) {
        returnParam += "&" + i + "=" + params[i];
      }

      console.log(returnParam);
      return returnParam;
    },

    /* 拿出价格和购物车里面的东西 */
    showPrice: function () {
      var cartDataItem = this.cart[0].carItems;
      var pushItem = [];
      /*  var countGood = 0
       var countPrice = 0 */

      for (let i = 0; i < cartDataItem.length; i++) {
        pushItem.push(cartDataItem[i]);
      }
      /*  for (let i = 0; i < pushItem.length; i++) {
         countGood += parseInt(pushItem[i].count)
         countPrice += parseInt(pushItem[i].count) * pushItem[i].carItemPrice
       } */


      this.setData({
        pushItem: pushItem
        /*     countGood: countGood,
            countPrice: countPrice */

      });
      /* console.log(pushItem)
      console.log(countGood)
      console.log(countPrice) */
    },

    /* 产品的加减 */
    subNum: function (event) {
      let productData = this.shopProList;
      let index = event.currentTarget.dataset.id;
      let focusProduct = productData[index];
      console.log(focusProduct);
      --focusProduct.inCarCount;
      this.setData({
        shopProList: productData
      });
      this.dellProduct(focusProduct, 'sub');
    },
    addNum: function (event) {
      let productData = this.shopProList;
      let index = event.currentTarget.dataset.id;
      let focusProduct = productData[index];
      console.log(focusProduct);
      ++focusProduct.inCarCount; //添加购买数量

      this.setData({
        shopProList: productData
      });
      this.dellProduct(focusProduct, 'add');
    },
    //删除函数
    delectFromPushItem: function (index) {
      let pushItem = this.pushItem;
      pushItem.splice(index, 1);
      this.setData({
        pushItem: this.pushItem
      });
    },
    delectFromProduct: function (product) {
      let productData = this.shopProList;

      for (let i = 0; i < productData.length; i++) {
        if (product.id == productData[i].id) {
          productData[i].inCarCount = 0;
        }
      }

      this.setData({
        shopProList: productData
      });
    },
    dellProduct: function (focusProduct, Ptype, measureId) {
      console.log('========0=======', focusProduct);
      let productData = this.shopProList;
      let pushItem = this.pushItem;

      if (!measureId) {
        console.log('=====1=====');
        measureId = 0;
      }

      if (!!measureId) {
        console.log('=====2=====');

        if (Ptype == 'sub') {
          var result = this.checkSub(focusProduct, measureId);
          console.log(result);

          if (result.ifOne) {
            this.delectFromPushItem(result.index);
            this.delectFromProduct(focusProduct);
          } else {
            --pushItem[result.index].count_offline;
          }
        }

        if (Ptype == 'add') {
          //检查是否在购物车里面数量为1
          let result = this.checkAdd(focusProduct, measureId);

          if (result.have) {
            //如果在那么就给他的数量加1
            ++pushItem[result.index].count_offline;
          } else {
            focusProduct.count_offline = 1;
            pushItem.push(focusProduct);
          }
        }

        console.log(pushItem);
        this.getPriceAndCount();
        this.setData({
          pushItem: pushItem
        });
      } else {
        console.log('=====3=====');

        if (Ptype == 'sub') {
          console.log('=====sub====='); //检查是否在购物车里面

          var result = this.checkSub(focusProduct);
          console.log(result);

          if (result.ifOne) {
            //如果在那么就给他删了
            //他的index有了
            this.delectFromPushItem(result.index);
          } else {
            --pushItem[result.index].count_offline;
          }
        }

        if (Ptype == 'add') {
          console.log('=====add====='); //检查是否在购物车里面数量为1

          var result = this.checkAdd(focusProduct);

          if (result.have) {
            //如果在那么就给他的数量加1
            ++pushItem[result.index].count_offline;
          } else {
            focusProduct.count_offline = 1;
            pushItem.push(focusProduct);
          }
        }
      }

      console.log('===pushItem====', pushItem);
      this.getPriceAndCount();
      this.setData({
        pushItem: pushItem
      });
      this.showAnimation();
      this.setAppCart();
    },
    showAnimation: function () {
      let animation = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease-in-out'
      });
      animation.scale(1.5).step();
      animation.scale(1).step();
      this.setData({
        shopCount: animation.export()
      });
    },
    //做一个cart数据集和一个产品的数据集，
    //然后相互校对，一般是addNum时校对购物车里面的addCarNum时校对产品数据
    //所以cart的数据集很有必要
    //addNum的时候加入
    checkAdd: function (product, MeasureId) {
      console.log('===this.data.pushItem======', this.pushItem);
      let pushItem = this.pushItem;
      let result = {
        have: 0,
        index: -1
      };

      if (!pushItem) {
        let result = {
          have: 0,
          index: 0
        };
      }

      if (!MeasureId) {
        MeasureId = 0;
      }

      if (!!MeasureId) {
        for (let i = 0; i < pushItem.length; i++) {
          if (product.id == pushItem[i].id) {
            if (MeasureId == pushItem[i].measureCartensian.id) {
              result.have = 1;
              result.index = i;
            }
          }
        }
      } else {
        for (let i = 0; i < pushItem.length; i++) {
          if (product.id == pushItem[i].id) {
            result.have = 1;
            result.index = i;
          }
        }
      }

      return result;
    },
    checkSub: function (product, MeasureId) {
      let pushItem = this.pushItem;
      let result = {
        ifOne: 0,
        index: -1
      };

      if (!MeasureId) {
        MeasureId = 0;
      }

      if (!!MeasureId) {
        for (let i = 0; i < pushItem.length; i++) {
          if (product.id == pushItem[i].id) {
            console.log('----product  相等---------');

            if (pushItem[i].count_offline == 1) {
              if (MeasureId == pushItem[i].measureCartensian.id) {
                console.log('----measureCartensian  相等---------');
                result.ifOne = 1;
                result.index = i;
              }
            } else {
              if (MeasureId == pushItem[i].measureCartensian.id) {
                console.log('----measureCartensian  相等---------');
                result.ifOne = 0;
                result.index = i;
              }
            }
          }
        }
      } else {
        for (let i = 0; i < pushItem.length; i++) {
          if (product.id == pushItem[i].id) {
            if (pushItem[i].count_offline == 1) {
              console.log('-----------1--------------');
              result.ifOne = 1;
              result.index = i;
            } else {
              result.ifOne = 0;
              result.index = i;
            }
          }
        }
      }

      return result;
    },

    /* 初始化Nums  用传值方式 */
    //计算价格和数量
    getPriceAndCount: function () {
      let pushItem = this.pushItem;
      let countPrice = 0;
      let countGood = 0;

      for (let i = 0; i < pushItem.length; i++) {
        countGood += pushItem[i].count_offline;
        countPrice += pushItem[i].count_offline * pushItem[i].price;
      }

      countPrice = countPrice.toFixed(2);
      this.setData({
        countGood: countGood,
        countPrice: countPrice
      });

      if (this.countGood == 0) {
        this.closeZhezhao();
      }
      /* 计算setting的type分类incart数量 */


      console.log('=====this.data.shopInfo.shopTypes=====', this.shopInfo.shopTypes);
      console.log('=====this.data.pushItem=====', this.pushItem);
      let categories = this.shopInfo.shopTypes;

      for (let j = 0; j < categories.length; j++) {
        categories[j].hasInCartCount = 0;
      }

      for (let i = 0; i < pushItem.length; i++) {
        for (let j = 0; j < categories.length; j++) {
          if (pushItem[i].shopProductType == categories[j].id) {
            categories[j].hasInCartCount += pushItem[i].count_offline;
          }
        }
      }

      console.log('=====this.data.shopInfo.shopTypes=====', this.shopInfo.shopTypes);
      this.setData({
        shopInfo: this.shopInfo
      });
    },
    //操作购物车
    dellCart: function (focusProduct, Ptype, measureId) {
      let productData = this.shopProList;
      let pushItem = this.pushItem;

      if (!measureId) {
        measureId = 0;
      }

      if (!!measureId) {
        if (Ptype == 'sub') {
          //检查是否在购物车里面
          var result = this.checkSub(focusProduct, measureId);
          console.log(result);

          if (result.ifOne) {
            //如果在那么就给他删了
            //他的index有了
            this.delectFromPushItem(result.index);
            this.delectFromProduct(focusProduct);
          } else {
            --pushItem[result.index].count_offline;
          }
        }

        if (Ptype == 'add') {
          //检查是否在购物车里面数量为1
          var result = this.checkAdd(focusProduct, measureId);

          if (result.have) {
            //如果在那么就给他的数量加1
            ++pushItem[result.index].count_offline;
          } else {
            focusProduct.count_offline = 1;
            pushItem.push(focusProduct);
          }
        }
      } else {
        if (Ptype == 'sub') {
          //检查是否在购物车里面
          var result = this.checkSub(focusProduct);
          console.log(result);

          if (result.ifOne) {
            //如果在那么就给他删了
            //他的index有了
            this.delectFromPushItem(result.index);
            this.delectFromProduct(focusProduct);
          } else {
            --pushItem[result.index].count_offline;
          }
        }

        if (Ptype == 'add') {
          //检查是否在购物车里面数量为1
          var result = this.checkAdd(focusProduct);

          if (result.have) {
            //如果在那么就给他的数量加1
            ++pushItem[result.index].count_offline;
          } else {
            focusProduct.count_offline = 1;
            pushItem.push(focusProduct);
          }
        }
      }

      console.log(pushItem);
      this.setCartInProduct();
      this.getPriceAndCount();
      this.setData({
        pushItem: pushItem
      });
    },

    /* 购物车的加减 */
    subCartNum: function (e) {
      var that = this;
      var pushItem = this.pushItem;
      var focusCartItem = null;
      var index = e.currentTarget.dataset.id;
      console.log(pushItem);
      focusCartItem = pushItem[index];

      if (!!focusCartItem.measureCartensian) {
        this.dellCart(focusCartItem, 'sub', focusCartItem.measureCartensian.id);
      } else {
        this.dellCart(focusCartItem, 'sub');
      }
    },
    addCartNum: function (e) {
      var that = this;
      var pushItem = this.pushItem;
      var focusCartItem = null;
      var index = e.currentTarget.dataset.id;
      focusCartItem = pushItem[index];

      if (!!focusCartItem.measureCartensian) {
        this.dellCart(focusCartItem, 'add', focusCartItem.measureCartensian.id);
      } else {
        this.dellCart(focusCartItem, 'add');
      }
    },

    /* 获取数据 */
    getShopTypeData: function (param) {
      //根据把param变成&a=1&b=2的模式
      var customIndex = getApp().globalData.AddClientUrl('/shop_detail_' + param.addShopId + '.html'); 
      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("=====shopdata======", res.data);
          let dataArr = res.data.result.shopInfo;

          if (!res.data.result.shopInfo) {
            that.setData({
              shopInfo: null
            });
          } else {
            that.setData({
              shopInfo: dataArr
            });
          }

          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        },
        complete: function () {
          that.setData({
            canRefresh: true
          });
        }
      });
    },

    /* 获取数据 */
    getShopListData: function (param, ifAdd) {
      if (!ifAdd) {
        ifAdd = 1;
      } //根据把param变成&a=1&b=2的模式


      var customIndex = getApp().globalData.AddClientUrl('/more_product_list.html', param); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("=====shopListdata======", res.data);
          that.listPage.pageSize = res.data.pageSize;
          that.listPage.curPage = res.data.curPage;
          that.listPage.totalSize = res.data.totalSize;
          let dataArr = that.shopProList;

          if (ifAdd == 2) {
            dataArr = [];
          }

          if (!res.data.result || res.data.result.length == 0) {
            that.setData({
              shopProList: null
            });
          } else {
            if (dataArr == null) {
              dataArr = [];
            }

            dataArr = dataArr.concat(res.data.result);
            that.setData({
              shopProList: dataArr
            });
          }

          wx.hideLoading();
          that.setCartInProduct();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        },
        complete: function () {
          that.setData({
            canRefresh: true
          });
        }
      });
    },
    more_product_list_URLFun: function (params) {
      let resule = getApp().globalData.AddClientUrl("/more_product_list.html", params);
      return resule;
    },
    toProductDetail: function (event) {
      console.log("--------toProductDetail------");
      console.log(event.currentTarget.dataset.info);
      var info = event.currentTarget.dataset.info;
      wx.navigateTo({
        url: '../productDetail/index?id=' + info.id + "&addShopId=" + info.belongShopId
      });
    },

    /* 购物车加减 */
    postParams: function (data) {
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data);
          wx.hideLoading();
          that.setData({
            countGood: res.data.totalCarItemCount,
            countPrice: res.data.totalCarItemPrice,
            shopProList: that.shopProList
          });
          that.getCart();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    //items:[{productId:1,caratesianId:0,count:1}]
    createOrder: function () {
      if (!getApp().globalData.checkShopOpenTime()) {
        return;
      }

      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      console.log(this.pushItem);
      let pushItem = this.pushItem;
      let postParam = {
        postCarItemJson: {
          items: []
        }
      };

      for (let i = 0; i < pushItem.length; i++) {
        let item = {
          productId: '',
          caratesianId: '0',
          count: ''
        };
        item.productId = pushItem[i].id;

        if (!!pushItem[i].measureCartensian) {
          item.cartesianId = pushItem[i].measureCartensian.id;
        }

        postParam.shopId = pushItem[i].belongShopId;
        postParam.orderType = '0';
        item.count = pushItem[i].count_offline;
        postParam.postCarItemJson.items.push(item);
      }

      postParam.postCarItemJson = JSON.stringify(postParam.postCarItemJson);
      console.log(postParam);
      this.creatOrder_buyNowFun(postParam);
    },
    creatOrder_buyNowFun: function (data) {
      var customIndex = getApp().globalData.AddClientUrl("/buy_now.html", data, 'post');
      var that = this; // wx.showLoading({
      //   title: 'loading',
      //   mask: true
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          wx.hideLoading();
          console.log(res);

          if (res.data.errcode == '10001') {
            getApp().globalData.checkIfLogin();
            return;
          }

          if (!!res.data.orderNo) {
            wx.navigateTo({
              url: '/pages/edit_order/index?orderNo=' + res.data.orderNo
            });
          } else {
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /* 获取购物车 */
    getCart: function () {
      var customIndex = getApp().globalData.AddClientUrl("Client.User.CarItemList");
      var that = this; //拿custom_page

      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);

          if (res.data.errcode == '10001') {
            that.setData({
              cart: []
            });
          } else {
            if (!!res.data.result.length) {
              that.setData({
                cart: res.data.result
              });
              that.showPrice();
            } else {
              that.setData({
                cart: []
              });
              that.setData({
                pushItem: []
              });
              that.setData({
                showType: false
              });
            }
          }
        },
        fail: function (res) {}
      });
    },
    //提交规格产品
    submitMeasure: function (id) {
      var that = this;
      let focusProduct = this.MeasureItem;
      let measurementJson = this.measurementJson;
      let data = {};
      data.cartesianId = measurementJson.id;
      data.productId = focusProduct.id;
      data.shopId = focusProduct.belongShopId;
      data.count = 1;
      data.type = 'add';
      var customIndex = getApp().globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('--------add----------');
          console.log(res.data);
          that.setData({
            showGuigeType: false
          });
          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    //获取规格价格参数
    get_measure_cartesionFun: function () {
      console.log(this.MeasureItem);
      let productId = this.MeasureItem.id;
      let postStr = '';

      for (let i = 0; i < this.MeasureParams.length; i++) {
        postStr += this.MeasureParams[i].value + ',';
      }

      let param = {};
      param.productId = productId;
      param.measureIds = postStr;
      let customIndex = getApp().globalData.AddClientUrl("/get_measure_cartesion.html", param);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          that.setData({
            measurementJson: res.data
          });
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },

    /* 初始化 选规格 */
    chooseMeasureItem: function (event) {
      let productData = this.shopProList;
      let index = event.currentTarget.dataset.id;
      let focusProduct = productData[index];

      for (let i = 0; i < focusProduct.measureTypes.length; i++) {
        focusProduct.measureTypes[i].checkedMeasureItem = 0; //初始化选择的数据

        let param = {};
        param.name = focusProduct.measureTypes[i].name;
        param.value = focusProduct.measureTypes[i].productAssignMeasure[0].id;
        this.MeasureParams.push(param);
      }

      this.setData({
        showGuigeType: true,
        MeasureItem: focusProduct
      });
      this.get_measure_cartesionFun();
    },
    //选择规格小巷的---显示
    radioChange: function (e) {
      let index = e.currentTarget.dataset.index;
      let indexJson = getApp().globalData.getSpaceStr(index, '-'); //console.log(indexJson)

      let focusItem = this.MeasureItem;
      focusItem.measureTypes[indexJson.str1].checkedMeasureItem = indexJson.str2;
      this.setData({
        MeasureItem: focusItem
      });
    },
    //选择规格小巷---获取数据
    chooseMeasure: function (e) {
      console.log(e.detail.value);
      let chooseMeasureJson = getApp().globalData.getSpaceStr(e.detail.value, '-');
      console.log(chooseMeasureJson);

      for (let i = 0; i < this.MeasureParams.length; i++) {
        if (this.MeasureParams[i].name == chooseMeasureJson.str1) {
          this.MeasureParams[i].value = chooseMeasureJson.str2;
        }
      }

      this.get_measure_cartesionFun();
    },
    closeGuigeZhezhao: function () {
      this.setData({
        showGuigeType: false
      });
      this.MeasureParams = [];
    },
    setCartInProduct: function () {
      console.log('====setCartInProduct.shopProList=====', this.shopProList);
      console.log('====setCartInProduct.pushItem=====', this.pushItem);
      let productData = this.shopProList;
      let pushItem = this.pushItem;

      if (productData != null) {
        for (let j = 0; j < productData.length; j++) {
          productData[j].inCarCount = 0;
        }

        for (let i = 0; i < pushItem.length; i++) {
          for (let j = 0; j < productData.length; j++) {
            if (pushItem[i].id == productData[j].id) {
              productData[j].inCarCount += pushItem[i].count_offline;
            }
          }
        }

        this.setData({
          shopProList: productData
        });
      }

      if (pushItem.length !== 0) {
        this.getPriceAndCount();
      }

      this.setAppCart();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom2: function () {
      var that = this;
      console.log("=======bottom======", this.canRefresh);

      if (this.canRefresh) {
        this.setData({
          canRefresh: false
        });
        setTimeout(function () {
          if (that.listPage.totalSize > that.listPage.curPage * that.listPage.pageSize) {
            that.listPage.page++;
            that.params.page++;
            that.getShopListData(that.params);
          }
        }, 300);
      }
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style scoped>
@import "./index.css";
</style>